package cn.kingshion.juc;

import java.util.concurrent.CountDownLatch;

/**
 * 闭锁：
 *      具体应用：多模块的后台数据统计，运用多线程技术分别对多个模块进行统计，然后最后对结果进行汇总。
 */
public class CountDownLatchTest {
    public static void main(String[] args) {
        final CountDownLatch latch = new CountDownLatch(5);
        LatchDemo latchDemo = new LatchDemo(latch);

        long start = System.currentTimeMillis();

        for (int i = 0; i < 5; i++) {
            new Thread(latchDemo).start();
        }

        try {
            latch.await();
        } catch (InterruptedException e) {


        }
        // 要求主线程在前面的十个线程都完成的前提下才开始执行。
        // 使用 闭锁的操作就可以保证一个线程在某一批多线程任务统一结束后再执行；
        long end = System.currentTimeMillis();
        System.out.println("耗费时间：" + (end - start));
    }
}

class LatchDemo implements Runnable {

    private CountDownLatch latch;

    public LatchDemo(CountDownLatch latch) {
        this.latch = latch;
    }

    @Override
    public void run() {

        synchronized (this) {
            try {
                for (int i = 0; i < 50000; i++) {
                    if (i % 2 == 0) {
                        System.out.println(i);
                    }
                }
            } finally {
                latch.countDown();
            }
        }
    }
}
